
/**
 * 类别添加、编辑窗口
 * 
 * @param {}
 *            config
 */
var CreateCatWindow = function(config) {

	// 将字段加入到form中，以利用form进行样式排列
	this.createForm = new Ext.FormPanel({
				labelWidth : 70,
				labelAlign : 'right',
				url : '',
				bodyStyle : 'padding:10px 10px 0',
				autoScroll : false,
				items : [new Ext.form.TextField({
									fieldLabel : '类别名称',
									name : 'catname',
									id : 'catname',
									width : 150
								}), new Ext.form.TextField({
									hidden : true,
									width : 10,
									name : 'catid',
									id : 'catid'
								})]
			});

	Ext.apply(this, config);
	CreateCatWindow.superclass.constructor.call(this, {
				id : 'CreateCatWindow',
				closeAction : 'hide',
				layout : 'fit',
				width : 300,
				height : 150,
				modal : true,
				title : '联系人分类',
				items : this.createForm,
				buttons : [{
							text : '确定',
							handler : function(button, e) {
								if (this.actionType == "addNew") {
									this.doCreate(e);
								} else {
									this.doUpdate(e);
								}

							},
							scope : this
						}, {
							text : '取消',
							handler : function(button, e) {
								this.resetInput();
								this.fireEvent('cancelClicked', this, e);
								if (this.cancelHandler) {
									this.cancelHandler.call(this.scope || this,
											this, e);
								} else {
									this.hide();
								}
							},
							scope : this
						}]
			});
};

Ext.extend(CreateCatWindow, Ext.Window, {
	/** 操作类型 */
	actionType : null,
	/** 新建表单 */
	createForm : null,
	/** 确定按钮事件处理器 */
	okHandler : null,
	/** 取消按钮事件处理器 */
	cancelHandler : null,
	/** 事件触发时对象的工作域 */
	scope : null,

	/**
	 * 显示窗口
	 */
	showWindow : function(btn) {
		if (btn.id == "addCat") {
			this.actionType = "addNew";
		} else if (btn.id == "editCat") {
			this.actionType = "edit";
		} else if (btn.id == "deleteCat") {
			this.actionType = "delete";
		}
		var form = this.createForm.getForm();
		if (this.actionType == "edit") {
			this.show();
			var node = Ext.getCmp("addrCatTree").getSelectionModel()
					.getSelectedNode();
			this.createForm.get('catname').setValue(node.text);
			this.createForm.get('catid').setValue(node.id);
		} else if (this.actionType == "addNew") {
			this.show();
			form.reset();
		} else if (this.actionType == "delete") {
			Ext.MessageBox.confirm('请确认', '是否删除所选分类及其下所有联系人？', this.doDelete);

		}

	},

	/**
	 * 将输入框清空
	 */
	resetInput : function() {
		var form = this.createForm.getForm();
		form.reset();
	},

	/**
	 * 新建
	 */
	doCreate : function(event) {
		var form = this.createForm.getForm();

		if (form.isValid()) {
			form.submit({
				url : context
						+ "/app/addressbook.do?method=addPersonAddrBookCatgory",
				waitMsg : '保存中...',
				method : 'POST',/**/
				scope : this,
				success : function(form, action) {

					this.resetInput();
					// 执行确定处理
					this.fireEvent('okClicked', this);
					if (this.okHandler) {
						this.okHandler.call(this.scope || this, this, event);
					} else {
						this.hide();
					}
					Ext.getCmp("addrCatTree").getRootNode().reload();
					Ext.getCmp("addrCatTree").getTopToolbar().items
							.get('editCat').setDisabled(true);
					Ext.getCmp("addrCatTree").getTopToolbar().items
							.get('deleteCat').setDisabled(true);

				},
				failure : function(form, action) {
					if (action.failureType === Ext.form.Action.CONNECT_FAILURE) {
						Ext.Msg.alert('保存失败', 'Status:'
										+ action.response.status + ': '
										+ action.response.statusText);
					}
					if (action.failureType === Ext.form.Action.SERVER_INVALID) {
						// server responded with success = false
						Ext.Msg.alert('保存失败', action.result.errors.errormsg);
					}

				}
			});

		} else {
			Ext.MessageBox.alert('错误', '请修正非法数据后再保存！');
			return;
		}
	},

	/**
	 * 更新
	 */
	doUpdate : function(event) {
		var form = this.createForm.getForm();

		if (form.isValid()) {
			form.submit({
				url : context + "/app/addressbook.do?method=saveAddrBookCat",
				waitMsg : '保存中...',
				method : 'POST',/**/
				scope : this,
				success : function(form, action) {

					this.resetInput();
					// 执行确定处理
					this.fireEvent('okClicked', this);
					if (this.okHandler) {
						this.okHandler.call(this.scope || this, this, event);
					} else {
						this.hide();
					}
					Ext.getCmp("addrCatTree").getRootNode().reload();
					Ext.getCmp("addrCatTree").getTopToolbar().items
							.get('editCat').setDisabled(true);
					Ext.getCmp("addrCatTree").getTopToolbar().items
							.get('deleteCat').setDisabled(true);

				},
				failure : function(form, action) {
					if (action.failureType === Ext.form.Action.CONNECT_FAILURE) {
						Ext.Msg.alert('保存失败', 'Status:'
										+ action.response.status + ': '
										+ action.response.statusText);
					}
					if (action.failureType === Ext.form.Action.SERVER_INVALID) {
						// server responded with success = false
						Ext.Msg.alert('保存失败', action.result.errors.errormsg);
					}

				}
			});

		} else {
			Ext.MessageBox.alert('错误', '请修正非法数据后再保存！');
			return;
		}
	},

	/**
	 * 删除分类
	 * 
	 * @param {}
	 *            event
	 */
	doDelete : function(event) {
		var node = Ext.getCmp("addrCatTree").getSelectionModel()
				.getSelectedNode();
		var url = context + '/app/addressbook.do?method=delAddrBookCat&cid='
				+ node.id;

		Ext.Ajax.request({
					// 请求地址
					url : url,
					scriptTag : true,
					// 成功时回调
					success : function(response, options) {
						var json = response.responseText;
						var o = Ext.util.JSON.decode(json);

						if (o.success) {
							Ext.getCmp("addrCatTree").getRootNode().reload();
							Ext.getCmp("addrCatTree").getTopToolbar().items
									.get('editCat').setDisabled(true);
							Ext.getCmp("addrCatTree").getTopToolbar().items
									.get('deleteCat').setDisabled(true);

							var url = context
									+ "/app/addressBook/blank.jsp?rd="
									+ new Date().getTime();
							Ext.get('frm').dom.src = url;
							Ext.Msg.alert('提示', '删除分类成功');
						} else {
							return '[]';
							Ext.Msg.alert('提示', '删除分类失败');
						}
					}
				});
	},

	// private
	initComponent : function() {
		CreateCatWindow.superclass.initComponent.call(this);
		this.addEvents(
				/**
				 * @event okClicked 当确定按钮被点击时触发
				 * @param {CreateCatWindow}
				 *            this
				 */
				'okClicked',
				/**
				 * @event okClicked 当取消按钮被点击时触发
				 * @param {CreateCatWindow}
				 *            this
				 */
				'cancelClicked');
	}

});

FeedPanel = function(config) {
	Ext.apply(this, config);
	FeedPanel.superclass.constructor.call(this, {
		id : 'addrCatTree',
		region : 'west',
		title : '我的通讯录',
		split : false,
		width : 270,
		minSize : 175,
		maxSize : 400,
		collapsible : false,
		margins : '0 0 0 0',
		// cmargins:'0 5 5 5',
		rootVisible : false,
		lines : false,
		autoScroll : true,
		collapseFirst : false,
		tbar : [{
					iconCls : 'add-icon',
					id : 'addCat',
					text : '添加分类',
					tooltip : '添加分类',
					handler : this.showWindow,
					scope : this
				}, {
					id : 'editCat',
					iconCls : 'edit-icon',
					text : '编辑',
					tooltip : '编辑分类',
					disabled : true,
					handler : this.showWindow,
					scope : this
				}, {
					id : 'deleteCat',
					iconCls : 'delete-icon',
					text : '删除',
					tooltip : '删除分类',
					disabled : true,
					handler : this.showWindow,
					scope : this
				}],
		loader : new Ext.tree.TreeLoader({
					dataUrl : context
							+ '/app/addressbook.do?method=personAddressBookTree'
				}),

		listeners : {
			'click' : function(node) {
				if (node == null)
					return;
				var url = context + "/app/addressbook.do?method=query&catid="
						+ node.id + "&rd=" + new Date().getTime();

				if (node.id == "-1" || node.id == "-2") {
					document.getElementById('frm').src = url;
					// this.fireEvent('feedselect', node.attributes);
					this.getTopToolbar().items.get('editCat').setDisabled(true);
					this.getTopToolbar().items.get('deleteCat')
							.setDisabled(true);
				} else {
					document.getElementById('frm').src = url;
					this.getTopToolbar().items.get('editCat')
							.setDisabled(false);
					this.getTopToolbar().items.get('deleteCat')
							.setDisabled(false);
				}

			}
		},

		root : new Ext.tree.AsyncTreeNode({
					id : '-99',
					expanded : true
				})
	});

	this.feeds = this.root.appendChild(new Ext.tree.TreeNode({
				text : 'My Feeds',
				cls : 'feeds-node',
				expanded : true
			}));

	this.getSelectionModel().on({
		'beforeselect' : function(sm, node) {
			return node.isLeaf();
		},
		scope : this
	});

	this.addEvents({
				feedselect : true
			});

	this.on('contextmenu', this.onContextMenu, this);
};

Ext.extend(FeedPanel, Ext.tree.TreePanel, {
	contentPanel : null,
	onContextMenu : function(node, e) {
		if (!this.menu) { // create context menu on first right click
			this.menu = new Ext.menu.Menu({
						id : 'feeds-ctx',
						items : [{
									id : 'load',
									iconCls : 'load-icon',
									text : 'Load Feed',
									scope : this,
									handler : function() {
										this.ctxNode.select();
									}
								}, {
									text : 'Remove',
									iconCls : 'delete-icon',
									scope : this,
									handler : function() {
										this.ctxNode.ui
												.removeClass('x-node-ctx');
										this
												.removeFeed(this.ctxNode.attributes.url);
										this.ctxNode = null;
									}
								}, '-', {
									iconCls : 'add-feed',
									text : 'Add Feed',
									handler : this.showWindow,
									scope : this
								}]
					});
			this.menu.on('hide', this.onContextHide, this);
		}
		if (this.ctxNode) {
			this.ctxNode.ui.removeClass('x-node-ctx');
			this.ctxNode = null;
		}
		if (node.isLeaf()) {
			this.ctxNode = node;
			this.ctxNode.ui.addClass('x-node-ctx');
			this.menu.items.get('load').setDisabled(node.isSelected());
			this.menu.showAt(e.getXY());
		}
	},

	onContextHide : function() {
		if (this.ctxNode) {
			this.ctxNode.ui.removeClass('x-node-ctx');
			this.ctxNode = null;
		}
	},

	showWindow : function(btn) {
		if (!this.win) {
			this.win = new CreateCatWindow();
		}
		this.win.showWindow(btn);
	},

	selectFeed : function(url) {
		this.getNodeById(url).select();
	},

	removeFeed : function(url) {
		var node = this.getNodeById(url);
		if (node) {
			node.unselect();
			Ext.fly(node.ui.elNode).ghost('l', {
						callback : node.remove,
						scope : node,
						duration : .4
					});
		}
	},

	addFeed : function(attrs, inactive, preventAnim) {
		var exists = this.getNodeById(attrs.url);
		if (exists) {
			if (!inactive) {
				exists.select();
				exists.ui.highlight();
			}
			return;
		}
		Ext.apply(attrs, {
					iconCls : 'feed-icon',
					leaf : true,
					cls : 'feed',
					id : attrs.url
				});
		var node = new Ext.tree.TreeNode(attrs);
		this.feeds.appendChild(node);
		if (!inactive) {
			if (!preventAnim) {
				Ext.fly(node.ui.elNode).slideIn('l', {
							callback : node.select,
							scope : node,
							duration : .4
						});
			} else {
				node.select();
			}
		}
		return node;
	},

	// prevent the default context menu when you miss the node
	afterRender : function() {
		FeedPanel.superclass.afterRender.call(this);
		this.el.on('contextmenu', function(e) {
					e.preventDefault();
				});
	}
});

Ext.reg('appfeedpanel', FeedPanel);